//
//  MCUserinfoViewController.swift
//  WisdomSpace
//
//  Created by goulela on 2017/9/4.
//  Copyright © 2017年 MC. All rights reserved.
//

import UIKit

class MCClerkDetailViewController: MCViewController {
    
    var model = MCClerkManageModel()
    public var isNew = false // 是否新增店员
    {
        didSet {
            isEdit = isNew
        }
    }
    private var isEdit = false // 是否编辑
    private var clerkId = 0 // 店员Id

    private var dataArray = [String]()

    private var newArray = ["头像","姓名","手机号","员工身份","登录密码","配送社区"]
    private var detalArray = ["头像","姓名","手机号","员工身份","登录密码","配送社区","佣金明细"]

    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initUI()
        
        
        baseSetting()
        
        
        changeUI(isNew: isNew, isEdit: isNew)
        
        
        sendNetworking()
    }

    // MARK: - Delegate
    // MARK: - Action
    @objc func rightItemClicked() {
        
        let level = MCLevelConversion(level: model.level).level
        

        if !isNew {
            if level == MCRole_manager {
                MCHUD_text(message: "不允许操作店长信息", view: self.view, delay: 1.2)
                return
            }
        }
        
        
        if isNew {   // 新增店员
            uploadImage(image: iconImageView.image!)
        } else {     // 编辑信息
            self.view.endEditing(true)
            
            if rightButton.isSelected {
                uploadImage(image: iconImageView.image!)
                return
            }
            
            
            isEdit = !rightButton.isSelected
            
            
            
            changeUI(isNew: isNew, isEdit: isEdit)
        }
    }
    
    
    @objc func deleteButtonClicked() {
        
        if MCLevelConversion(level: model.level).level == MCRole_manager {
            MCHUD_text(message: "店长不可删除", view: self.view, delay: 1.2)
            return
        }

        
        MCAlterController_twoOptions(vc: self, message: "是否删除？", confirm: {
            let para = [
                "clerkId" : self.model.clerkId,
                ] as [String : Any]
            
            MCNetwork.POST(JAVA_deleteClerk, para, vc: self, success: { (data) in
                
                MCHUD_text(message: "成功删除该店员", view: self.view, delay: 1.2)
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.2, execute: {
                    self.navigationController?.popViewController(animated: true)
                })
                
            }, failure: nil)
        }, cancle: nil)
    }
    
 
    
    // MARK: - Network
    func sendNetworking() {
        
        if !isNew {
            self.iconImageView.sd_setImage(with: URL.init(string: model.picture), placeholderImage: #imageLiteral(resourceName: "Reuse_placeholder_1_1"))
            self.nameTextField.text = model.nickName
            self.phoneTextField.text = model.userName
            self.identifierLabel.text = MCLevelConversion(level: model.level).levelName
            self.identifierLabel.textColor = UIColor.MCGray_middle
            clerkId = model.clerkId
        }
    }
    
    
    func sendNetworking_addClerk(picture:String) {
        
        var level = 0
        
        if identifierLabel.text == MCGetConfiguration_assistantName() {
            level = MCRole_assistant
        } else {
            level = MCRole_salesStaff
        }
        
        let password = passwordTextField.text ?? ""

        
        if level == 0 {
            MCHUD_text(message: "请选择员工身份", view: self.view, delay: 1.2)
            return
        }
        
        if (nameTextField.text?.isEmpty)! {
            MCHUD_text(message: "请填写姓名", view: self.view, delay: 1.2)
            return
        }
        
        if password.isEmpty {
            MCHUD_text(message: "请填写登录密码", view: self.view, delay: 1.2)
            return
        }
        
        
        if phoneTextField.text?.count != 11 {
            MCHUD_text(message: "请填写正确的手机号", view: self.view, delay: 1.2)
            return
        }

        
        
        
        let para = [
            "level" : level,
            "mobilePhone" : phoneTextField.text ?? "",
            "nickName" : nameTextField.text ?? "",
            "picture" : picture,
            "clerkId" : clerkId,
            "password": password.MCMD5()
            ] as [String : Any]
        
        
        
        MCNetwork.POST(JAVA_addClerk, para, vc: self, success: { (data) in
            
            let data = data.numberValue
            
            if self.clerkId == 0 {
                MCAlterController_twoOptions(vc: self, message: "新增店员成功，是否继续维护配送社区信息？", confirm: {
                    let vc = MCCommunityViewController()
                    vc.clerkId = data.intValue
                    MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
                }, cancle: {
                    MCHUD_text(message: "新增成功", view: self.view, delay: 1.2)
                    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.2, execute: {
                        self.navigationController?.popViewController(animated: true)
                    })
                })
            } else {
                MCHUD_text(message: "修改成功", view: self.view, delay: 1.2)
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.2, execute: {
                    self.navigationController?.popViewController(animated: true)
                })
            }
            
        }, failure: nil)
        
    }
    
    // MARK: - Method
    func baseSetting() {
        self.view.backgroundColor = UIColor.MCGray_light
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: rightButton)
    }
    
    func initUI() {
        
        view.addSubview(tableView)
        tableView.snp.remakeConstraints { (make) -> Void in
            make.left.right.top.equalTo(view)
            make.height.equalTo(dataArray.count * 50 + 30)
        }
        
        
        view.addSubview(deleteButton)
        deleteButton.snp.remakeConstraints { (make) ->Void in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.top.equalTo(tableView.snp.bottom).offset(50)
            make.height.equalTo(36)
        }
    }
    
    // 图库
    func libraryClicked() {
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
            let vc = UIImagePickerController()
            vc.delegate = self
            vc.allowsEditing = true
            vc.sourceType = UIImagePickerControllerSourceType.photoLibrary
            self.present(vc, animated: true, completion: { })
        }
    }
    
    // 拍照
    func cameraClicked() {
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
            
            let availableMeidatypes : NSArray = UIImagePickerController.availableMediaTypes(for: UIImagePickerControllerSourceType.camera)! as NSArray
            
            var canTakePicture = false
            
            for mediaType in availableMeidatypes {
                
                let str = mediaType as? String
                
                if str == String(kUTTypeImage) {
                    canTakePicture = true
                    break
                }
            }
            
            guard canTakePicture else {
                return
            }
            
            let vc = UIImagePickerController()
            vc.delegate = self
            vc.allowsEditing = true
            vc.sourceType = UIImagePickerControllerSourceType.camera
            vc.mediaTypes = NSArray(object: String(kUTTypeImage)) as! [String]
            self.present(vc, animated: true, completion: { })
            
        }
    }
    
    func uploadImage(image:UIImage) {
        let imageData = UIImageJPEGRepresentation(image, 0.1)
        let base = imageData?.base64EncodedString() ?? ""
        
        let para = [
            "catalog" : "3",
            "suffix"  : "png",
            "imgBase" : base
            ] as [String : Any]
        
        MCNetwork.POST(JAVA_imageBasePath, para, vc: self, success: { (data) in
            let imgUrl = data.stringValue
            self.sendNetworking_addClerk(picture: imgUrl)
        }, failure: nil)
    }
    
    func changeUI(isNew:Bool,isEdit:Bool) {
        rightButton.isSelected = isEdit
        deleteButton.isHidden = isEdit
        
        if isEdit {
            self.title = "修改店员信息"
            dataArray = newArray
        } else {
            dataArray = detalArray
            self.title = "店员信息"
        }
        
        
        if isNew {
            self.title = "新增店员"
        } else {
            if isEdit {
                self.title = "修改店员信息"
            } else {
                dataArray = detalArray
            }
        }
        
        tableView.snp.remakeConstraints { (make) -> Void in
            make.left.right.top.equalTo(view)
            make.height.equalTo(dataArray.count * 50 + 30)
        }

        tableView.reloadData()
    }

    
    
    
    // MARK: - Setter & Getter
    lazy var rightButton: UIButton = {
        let button = UIButton.init(type: UIButtonType.custom)
        button.frame = CGRect.init(x: 0, y: 0, width: 50, height: 40)
        button.titleLabel?.font = MCFont(14)
        button.setTitleColor(UIColor.MCWords, for: .normal)
        button.setTitle("修改", for: .normal)
        button.setTitle("保存", for: .selected)
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignment.right
        button.addTarget(self, action: #selector(rightItemClicked), for: .touchUpInside)
        return button
    }()
    
    
    
    fileprivate lazy var tableView: MCTableView = {
        let tableView = MCTableView.init(frame: CGRect.zero, style: UITableViewStyle.plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor.MCGray_light
        tableView.isScrollEnabled = false
        return tableView
    }()
    
    fileprivate lazy var iconImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.layer.cornerRadius = 25
        imageView.layer.masksToBounds = true
        imageView.layer.borderColor = UIColor.MCGray_light.cgColor
        imageView.layer.borderWidth = 1
        imageView.image = #imageLiteral(resourceName: "Reuse_icon")
        imageView.isUserInteractionEnabled = true
        return imageView
    }()
    
    fileprivate lazy var nameTextField: MCTextFiled = {
        let tf = MCTextFiled()
        tf.font = MCFont(14)
        tf.textAlignment = NSTextAlignment.right
        tf.textColor = UIColor.MCGray_middle
        tf.placeholder = "请填写姓名"
        return tf
    }()
    
    
    fileprivate lazy var phoneTextField: MCTextFiled = {
        let tf = MCTextFiled()
        tf.font = MCFont(14)
        tf.textAlignment = NSTextAlignment.right
        tf.textColor = UIColor.MCGray_middle
        tf.placeholder = "请填写手机号"

        return tf
    }()
    
    fileprivate lazy var passwordTextField: MCTextFiled = {
        let tf = MCTextFiled()
        tf.font = MCFont(14)
        tf.textAlignment = NSTextAlignment.right
        tf.textColor = UIColor.MCGray_middle
        tf.keyboardType = UIKeyboardType.asciiCapable
        tf.placeholder = "请输入员工的密码"
        return tf
    }()

    
    lazy var identifierImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.image = #imageLiteral(resourceName: "Ticket_choose")
        return imageView
    }()
    
    fileprivate lazy var identifierLabel: UILabel = {
        let label = UILabel()
        label.font = MCFont(14)
        label.textColor = UIColor.MCPlaceHolder
        label.text = "请选择员工身份"
        return label
    }()


    
    
    
    
    lazy var deleteButton: UIButton = {
        let button = UIButton.init(type: UIButtonType.custom)
        button.backgroundColor = UIColor.MCMain
        button.layer.cornerRadius = 18
        button.layer.masksToBounds = true
        button.titleLabel?.font = MCFont(14)
        button.setTitle("店员离职，删除档案", for: UIControlState.normal)
        button.setTitleColor(UIColor.white, for: UIControlState.normal)
        button.addTarget(self, action: #selector(deleteButtonClicked), for: UIControlEvents.touchUpInside)
        return button
    }()
}



extension MCClerkDetailViewController: UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch indexPath.item {
        case 0:
            return 80
        default:
            return 50
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = UITableViewCell.init(style: UITableViewCellStyle.value1, reuseIdentifier: "cell")
        
        cell.selectionStyle = UITableViewCellSelectionStyle.none
        cell.backgroundColor = UIColor.white
        
        cell.textLabel?.font = MCFont(14)
        cell.textLabel?.text = dataArray[indexPath.row]
        
        if indexPath.row != (self.dataArray.count - 1) {
            let line = UIView()
            line.backgroundColor = UIColor.MCGray_light
            cell.addSubview(line)
            line.snp.remakeConstraints { (make) -> Void in
                make.right.bottom.equalTo(cell)
                make.left.equalTo(cell).offset(15)
                make.height.equalTo(1)
            }
        }
        
        if indexPath.row == 0 {
            cell.addSubview(iconImageView)
            if isEdit {
                cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
                iconImageView.snp.remakeConstraints { (make) -> Void in
                    make.centerY.equalTo(cell)
                    make.right.equalTo(-30)
                    make.size.equalTo(CGSize.init(width: 50, height: 50))
                }
            } else {
                cell.accessoryType = UITableViewCellAccessoryType.none
                iconImageView.snp.remakeConstraints { (make) -> Void in
                    make.centerY.equalTo(cell)
                    make.right.equalTo(-15)
                    make.size.equalTo(CGSize.init(width: 50, height: 50))
                }
            }
            
        }
        
        if indexPath.row == 1 {
            
            nameTextField.isEnabled = isEdit
            
            cell.addSubview(nameTextField)
            nameTextField.snp.remakeConstraints { (make) -> Void in
                make.top.bottom.equalTo(cell)
                make.right.equalTo(-15)
                make.width.equalTo(MCScreenWidth/2)
            }
        }
        
        if indexPath.row == 2 {
            
            // 手机号只允许新增 不能修改
            if isNew {
              phoneTextField.isEnabled = true
            } else {
                phoneTextField.isEnabled = false
            }
            cell.addSubview(phoneTextField)
            phoneTextField.snp.remakeConstraints { (make) -> Void in
                make.top.bottom.equalTo(cell)
                make.right.equalTo(-15)
                make.width.equalTo(MCScreenWidth/2)
            }
        }
        
        if indexPath.row == 3 {
            
            cell.addSubview(identifierImageView)
            cell.addSubview(identifierLabel)

            
            if isEdit {
                identifierImageView.snp.remakeConstraints { (make) -> Void in
                    make.centerY.equalTo(cell)
                    make.right.equalTo(-15)
                    make.size.equalTo(CGSize.init(width: 9, height: 11))
                }
                identifierLabel.snp.remakeConstraints { (make) -> Void in
                    make.centerY.equalTo(cell)
                    make.right.equalTo(identifierImageView.snp.left).offset(-5)
                }
            } else {
                identifierImageView.snp.remakeConstraints { (make) -> Void in
                    make.centerY.equalTo(cell)
                    make.right.equalTo(-15)
                    make.size.equalTo(CGSize.init(width: 0, height: 0))
                }
                identifierLabel.snp.remakeConstraints { (make) -> Void in
                    make.centerY.equalTo(cell)
                    make.right.equalTo(identifierImageView.snp.left).offset(0)
                }
            }
        }
        
        if indexPath.row == 4 {
            passwordTextField.isEnabled = isEdit
            
            if isEdit {
                passwordTextField.text = ""
            } else {
                passwordTextField.text = "******"
            }
            
            cell.addSubview(passwordTextField)
            passwordTextField.snp.remakeConstraints { (make) -> Void in
                make.top.bottom.equalTo(cell)
                make.right.equalTo(-15)
                make.width.equalTo(MCScreenWidth/2)
            }
        }

        
        if indexPath.row == 6 || indexPath.row == 5 {
            cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
        }
        
        return cell
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        

        
        self.view.endEditing(true)
        
        switch indexPath.row {
        case 0:
            
            if !isEdit {
                return
            }
            
            let alterController = UIAlertController.init(title: "修改头像", message: nil, preferredStyle: UIAlertControllerStyle.actionSheet);
            let cancelAction = UIAlertAction.init(title: "取消", style: UIAlertActionStyle.cancel, handler: { (action) in
            })
            let libraryAction = UIAlertAction.init(title: "图库", style: UIAlertActionStyle.default, handler: { (action) in
                self.libraryClicked()
            })
            
            let cameraAction = UIAlertAction.init(title: "拍照", style: UIAlertActionStyle.default, handler: { (action) in
                self.cameraClicked()
            })
            
            alterController.addAction(cancelAction)
            alterController.addAction(libraryAction)
            alterController.addAction(cameraAction)
            
            self.present(alterController, animated: true, completion: {})
        case 3:
            if !isEdit {
                return
            }
            
            let alterController = UIAlertController.init(title: "员工身份", message: nil, preferredStyle: UIAlertControllerStyle.actionSheet);
            let cancelAction = UIAlertAction.init(title: "取消", style: UIAlertActionStyle.cancel, handler: { (action) in
            })
            let oneAction = UIAlertAction.init(title: MCGetConfiguration_assistantName(), style: UIAlertActionStyle.default, handler: { (action) in
                self.identifierLabel.text = MCGetConfiguration_assistantName()
                self.identifierLabel.textColor = UIColor.MCGray_middle

            })
            
            let twoAction = UIAlertAction.init(title: MCGetConfiguration_salesStaff(), style: UIAlertActionStyle.default, handler: { (action) in
                self.identifierLabel.text = MCGetConfiguration_salesStaff()
                self.identifierLabel.textColor = UIColor.MCGray_middle
            })
            
            alterController.addAction(cancelAction)
            alterController.addAction(oneAction)
            alterController.addAction(twoAction)
            
            self.present(alterController, animated: true, completion: {})
        case 5:
            let vc = MCCommunityViewController()
            vc.clerkId = model.clerkId
            MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
        case 6:
            let vc = MCMyCommissionViewController()
            vc.clerkId = self.model.clerkId
            MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)

        default:
            break
        }
    }
}

extension MCClerkDetailViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let mediaType = info[UIImagePickerControllerMediaType] as! String
        
        if mediaType == String(kUTTypeImage) {
            let originalImage : UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage
            
            let rect = info[UIImagePickerControllerCropRect] as! CGRect
            
            let editedImage = originalImage.MCImageCrop(toRect: rect)
            
            iconImageView.image = editedImage
            picker.dismiss(animated: true, completion: nil)
        }
    }
}


